//
//  ExamViewController.m
//  jinnengExam
//
//  Created by mac on 2020/8/12.
//  Copyright © 2020 jznrj. All rights reserved.
//

#import "ExamViewController.h"
#import "QuestionBankViewController.h"
#import "PBFlatBarButtonItems.h"
#import "JinnengExamViewController.h"
#import "ExamedViewController.h"
#import "PointViewControllerViewController.h"
#import "LoginViewController.h"
#import "ScanCodeViewController.h"
#import "OnlineExamViewController.h"
#import "BankTypeViewController.h"
#import "UserCenterViewController.h"
#import "EOnlineExamViewController.h"
#import "EOnlineTrainViewController.h"
#import "QuestionBankTypeViewController.h"
#import "SearchViewController.h"
#import "EOnlineVideoViewController.h"

@interface ExamViewController ()
@property(nonatomic) CGRect frame;
@property(nonatomic,strong) JznWebView *titleView;
@property(nonatomic, strong) WKWebViewJavascriptBridge *titleBridge;
@end

@implementation ExamViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    _frame = self.tabBarController.tabBar.frame;
    // Do any additional setup after loading the view.
    [self initView];
}

-(void) viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden =YES;
    self.tabBarController.tabBar.hidden = NO;
    self.tabBarController.tabBar.frame = _frame;
    [self requestPoint];
}
-(void) viewDidAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden =YES;
    self.tabBarController.tabBar.hidden = NO;
    self.tabBarController.tabBar.frame = _frame;
//    [self requestPoint];
}

-(void) initView{
     CGRect statusFrame = [[UIApplication sharedApplication] statusBarFrame];
     self.titleView  = [[JznWebView alloc]initWithFrame:_frame];
     [self.view addSubview:self.titleView];
     [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.height.mas_equalTo(self.titleHeight+statusFrame.size.height);
         make.width.left.equalTo(self.view);
         make.top.equalTo(self.view).offset(-(5+statusFrame.size.height));
     }];
    if(statusFrame.size.height<44){
        [self.titleView loadLocalFile:@"/ios_jinneng/jinnengTitle_new_small" type:@"html"];
    }else{
        [self.titleView loadLocalFile:@"/ios_jinneng/jinnengTitle_new" type:@"html"];
    }
     
     [self.view addSubview:self.jznWebView];
     [self.jznWebView mas_makeConstraints:^(MASConstraintMaker *make) {
          make.left.right.equalTo(self.view);
          make.top.equalTo(self.view).offset(self.titleHeight);
          if (@available(iOS 11.0, *)) {

              make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
          } else {
              make.bottom.equalTo(self.view);
          }
      }];
      self.view.backgroundColor = [UIColor whiteColor];
    [self.jznWebView loadLocalFile:@"/ios_jinneng/exam" type:@"html"];
    self.titleBridge = [WKWebViewJavascriptBridge bridgeForWebView:self.titleView];
    [self.titleBridge setWebViewDelegate:self];
    
    [self.jznWebView.scrollView.mj_header setBackgroundColor:[UIColor whiteColor]];
    self.jznWebView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestBanner];
        
    }];
    
    [self registerJSFunction];
    
}

-(void) requestPoint{
    NSString *url = [NSString stringWithFormat:@"%@/userRank/findUserScore",[URLUtil hostName]];
    NSDictionary *params = @{@"userId":[NSString stringWithFormat:@"%d",self.loginDto.userId]};
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        if(dataResult.code == 0){
            NSString *js = [NSString stringWithFormat:@"getPoint(%@)",dataResult.data];
            [self.titleView evaluateJavaScript:js completionHandler:nil];
        }else {
        }
    } failure:^(NSError *error) {
        
    }];
    
    NSString *url1 = [NSString stringWithFormat:@"%@/userEntry/userLoginCount",[URLUtil hostName]];
    NSDictionary *params1 = @{};
    [JZNRequestUtil requestUrl:url1 requestParams:params1 success:^(DataResult *dataResult) {
        if(dataResult.code == 0){
            NSString *js = [NSString stringWithFormat:@"getUserCount(%@)",dataResult.data];
            [self.titleView evaluateJavaScript:js completionHandler:nil];
        }else {
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void) requestBanner{
    NSString *url = [NSString stringWithFormat:@"%@/newsView/findScrollNews" ,[URLUtil hostName]];
    NSDictionary *params = @{@"module":@"[1]"};
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        if(dataResult.code == 0){
            NSMutableArray *array = [[NSMutableArray alloc]init];
            NSArray *dataArray = dataResult.data;
            [self.jznWebView.scrollView.mj_header endRefreshing];
            for(id data in dataArray){
                [array addObject:[NSString stringWithFormat:@"%@%@",[URLUtil hostName],[data objectForKey:@"titleImage"]]];
            }
            
            NSString *clear = [NSString stringWithFormat:@"getImageList(%@)",[array mj_JSONString]];
            [self.jznWebView evaluateJavaScript:clear completionHandler:nil];
            
            NSString *userid = [NSString stringWithFormat:@"getUserId(%d)",self.loginDto.userId];
            [self.jznWebView evaluateJavaScript:userid completionHandler:nil];
            
        }else {
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void) registerJSFunction{
    [self.webViewBridge registerHandler:@"toExam" handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^(){
            int type = [data[@"type"] intValue];
            [self requestPaper:type];

        });
    }];
    [self.titleBridge registerHandler:@"toSearch" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        dispatch_async(dispatch_get_main_queue(), ^(){

            SearchViewController *vc = [[SearchViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        });
        
    }];
    [self.titleBridge registerHandler:@"toUserCenter" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        dispatch_async(dispatch_get_main_queue(), ^(){

            UserCenterViewController *vc = [[UserCenterViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        });
        
    }];
    
    [self.webViewBridge registerHandler:@"toQuestionBank" handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^(){
            QuestionBankTypeViewController *vc = [[QuestionBankTypeViewController alloc]init];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        });
    }];
    
    [self.webViewBridge registerHandler:@"toOnlineExam" handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^(){
            OnlineExamViewController *vc = [[OnlineExamViewController alloc]init];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        });
    }];
    
    [self.webViewBridge registerHandler:@"toEOnlineExam" handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^(){
            EOnlineExamViewController *vc = [[EOnlineExamViewController alloc]init];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        });
    }];
    
    [self.webViewBridge registerHandler:@"toEOnlineTrain" handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^(){
            EOnlineTrainViewController *vc = [[EOnlineTrainViewController alloc]init];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        });
    }];
    
    
    [self.webViewBridge registerHandler:@"toEOnlineVideo" handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^(){
            EOnlineVideoViewController *vc = [[EOnlineVideoViewController alloc]init];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        });
    }];
    
    [self.titleBridge registerHandler:@"toPoint" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        dispatch_async(dispatch_get_main_queue(), ^(){

            PointViewControllerViewController *vc = [[PointViewControllerViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        });
        
    }];
    
    [self.titleBridge registerHandler:@"toScan" handler:^(id data, WVJBResponseCallback responseCallback) {
          
          dispatch_async(dispatch_get_main_queue(), ^(){
              NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
              if ([userDefault objectForKey:@"account"] == nil) {
                  LoginViewController *controller = [[LoginViewController alloc]init];
                  controller.tabIndex = 0;
                  controller.modalPresentationStyle = UIModalPresentationFullScreen;
                  [self presentModalViewController:controller animated:YES ];
                  return;
              }else{
                  ScanCodeViewController *learnNewsViewController = [[ScanCodeViewController alloc]init];
                  self.hidesBottomBarWhenPushed = YES;
                  [self.navigationController pushViewController:learnNewsViewController animated:YES];
              }
          });
          
      }];
}

-(void) requestPaper:(int) type{
    NSString *url;
    int time = 3*60;
    switch (type) {
        case 1:
            url = [NSString stringWithFormat:@"%@/exam/findDayCanAnswer",[URLUtil hostName]];
            time = 1*60;
            break;
        case 2:
            url = [NSString stringWithFormat:@"%@/exam/findWeekCanAnswer",[URLUtil hostName]];
            time = 10*60;
            break;
        case 3:
            url = [NSString stringWithFormat:@"%@/exam/findMonthCanAnswer",[URLUtil hostName]];
            time = 30*60;
            break;
        default:
            url = [NSString stringWithFormat:@"%@/exam/findDayCanAnswer",[URLUtil hostName]];
            time = 1*60;
            break;
    }
    NSDictionary *params = @{@"userId":[NSString stringWithFormat:@"%d",self.loginDto.userId]};
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        if(dataResult.code == 1102){
            JinnengExamViewController *vc = [[JinnengExamViewController alloc]init];
            self.hidesBottomBarWhenPushed = YES;
            vc.paper = [dataResult.data mj_JSONString];
            vc.time = time;
            vc.type = type;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(dataResult.code == 1101){
            ExamedViewController *vc = [[ExamedViewController alloc]init];
            self.hidesBottomBarWhenPushed = YES;
            vc.paper = [dataResult.data mj_JSONString];
            vc.type = type;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(dataResult.code == 1103){
            BankTypeViewController *vc = [[BankTypeViewController alloc]init];
            self.hidesBottomBarWhenPushed = YES;
            vc.time = time;
            vc.type = type;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [self.jznWebView.scrollView.mj_header beginRefreshing];
    [self requestPoint];
    NSString *js = [NSString stringWithFormat:@"getUserName('%@')",self.loginDto.userName];
    [self.titleView evaluateJavaScript:js completionHandler:nil];
    
    NSString *js1 = [NSString stringWithFormat:@"getCompanyName('%@')",self.loginDto.businessCompanyName];
    [self.titleView evaluateJavaScript:js1 completionHandler:nil];
}

- (void)tabBarController:(UITabBarController*) tabBarController didSelectViewController:(UIViewController*)viewController{
    if (self.tabBarController.tabBar.isHidden) {
        self.tabBarController.tabBar.hidden = NO;
        self.tabBarController.tabBar.frame = _frame;
    }
}

@end
